// pages/xunJianDetails/xunJianDetails.js
const httpRequest = require('../../utils/http_utils.js')
const moment = require('../../plug/moment.min.js');
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    title: '',
    success: '', //处理成功提示语
    error: '', //处理失败提示语
    info: '', //提示语
    items: [{
        name: '正常',
        value: '正常'
      },
      {
        name: '异常',
        value: '异常'
      }
    ],
    showNormal: false, //判断巡检结果是否异常
    showAbnormal: false,
    stateValue: false,
    Prohibit: false, //判断单选是否启用
    Submission: true, //判断详情和新增
    TaskType: '', //设备、设备间类型
    RowGuid: '', //设备ID
    GuidType: '', //设备类型
    PatrolList: [], //巡检项集合
    numValue: '', //数字输入框的值
    textValue: '', //文本输入框值
    textNam: 0, //文本输入框的数量
    FileGuid: [], //上传图片集合
    images: [], //图片集合
    picnum: 0, //上传图片数量
    height: 220, //高度
    IsAlarm: 0, //巡检结果
    Remarks: '', //问题反馈
    SpotTypes: null, //判断当前巡检类型
    ArraysList: [], //巡检项值集合
    imgs2: [], //用于过渡图片地址和rowguid关系
    rideoList: [], //单选集合
    namList: [], //数字框集合
    customHeight: 0, //自定义高度
  },

  //单选按钮
  radioChange: function(e) {
    var newarr = this.data.rideoList;
    var newArray = this.data.ArraysList;
    var param = {
      RowGuid: e.currentTarget.dataset.rowguid,
      Value: e.detail.value
    }
    var params = {
      "SpotType": e.currentTarget.dataset.spottype,
      "SpotGuid": e.currentTarget.dataset.rowguid,
      "SpotName": e.currentTarget.dataset.spotname,
      "AlemMax": e.currentTarget.dataset.alermmax,
      "AlemMin": e.currentTarget.dataset.alermmin,
      "CollectionValue": e.detail.value,
      "IsIntelligence": ""
    }
    for (var i = 0; i < newArray.length; i++) {
      if (newArray[i].SpotGuid == params.SpotGuid) {
        newArray.splice(i, 1)
      }
    }

    for (var i = 0; i < newarr.length; i++) {
      if (newarr[i].RowGuid == param.RowGuid) {
        newarr.splice(i, 1)
      }
    }
    newarr.push(param)
    newArray.push(params)
    this.setData({
      ArraysList: newArray,
      rideoList: newarr
    })
    let count = 0;
    newarr.map(elea => {
      if (elea.Value == '异常') {
        count = count + 1;
      }
      console.log(count + "------------单选异常数")
      this.countnum(count);
    })
  },

  //选择巡检项
  countnum: function(count) {
    console.log(this.data.PatrolList.length + "------------接口数据长度-----------" + this.data.ArraysList.length)
    if ((this.data.PatrolList.length - this.data.textNam) == this.data.ArraysList.length && count == 0) {
      console.log("正常")
      this.setData({
        showNormal: true,
        showAbnormal: false
      })
    } else {
      console.log("异常")
      this.setData({
        showAbnormal: true,
        showNormal: false
      })
    }
    if (this.data.showNormal == true) {
      this.setData({
        IsAlarm: 0
      })
    } else {
      this.setData({
        IsAlarm: 1
      })
    }
  },

  //选择状态
  tapState: function(e){
    console.log(JSON.stringify(e.currentTarget.dataset.state))
    if (e.currentTarget.dataset.state == '正常'){
      this.setData({
        showAbnormal: false,
        showNormal: true,
        IsAlarm: 0
      })
    }else{
      this.setData({
        showAbnormal: true,
        showNormal: false,
        IsAlarm: 1
      })
    }
  },

  inputInfo: function(e) {
    console.log(JSON.stringify(e.detail.value))
    this.setData({
      Remarks: e.detail.value
    })
  },

  //获取巡检项数字输入框
  itemInput: function(e) {
    if (e.detail.value == '') {
      return
    } else {
      if (e.detail.value > e.currentTarget.dataset.nummax) {
        this.setData({
          numValue: ''
        })
        e.detail.value = '';
      } else if (e.detail.value < e.currentTarget.dataset.nummin) {
        this.setData({
          numValue: ''
        })
        e.detail.value = '';
      }
      if (e.detail.value != '') {
        var newarr = this.data.namList;
        var newArray = this.data.ArraysList;

        var params = {
          "SpotType": e.currentTarget.dataset.spottype,
          "SpotGuid": e.currentTarget.dataset.rowguid,
          "SpotName": e.currentTarget.dataset.spotname,
          "AlemMax": e.currentTarget.dataset.alermmax,
          "AlemMin": e.currentTarget.dataset.alermmin,
          "CollectionValue": e.detail.value,
          "IsIntelligence": "",
        }
        for (var i = 0; i < newArray.length; i++) {
          if (newArray[i].SpotGuid == params.SpotGuid) {
            newArray.splice(i, 1)
          }
        }
        var param = {
          "RowGuid": e.currentTarget.dataset.rowguid,
          "AlemMax": e.currentTarget.dataset.alermmax,
          "AlemMin": e.currentTarget.dataset.alermmin,
          "Value": e.detail.value
        }

        for (var i = 0; i < newarr.length; i++) {
          if (newarr[i].RowGuid == param.RowGuid) {
            newarr.splice(i, 1)
          }
        }
        newArray.push(params)
        newarr.push(param)
        console.log(JSON.stringify(newarr) + "----------------------数字集合")
        this.setData({
          ArraysList: newArray,
          namList: newarr
        })
        let count = 0;
        newarr.map(ele => {
          if (ele.AlemMax < ele.Value || ele.Value < ele.AlemMin) {
            count = count + 1;
          }
          console.log(count + "------------数字异常数")
          this.countnum(count);
        })
      }

    }
  },

  //文本输入框
  textInput: function(e) {
    if (e.detail.value == '') {
      return
    } else {
      var newArray = this.data.ArraysList;

      var params = {
        "SpotType": e.currentTarget.dataset.spottype,
        "SpotGuid": e.currentTarget.dataset.rowguid,
        "SpotName": e.currentTarget.dataset.spotname,
        "AlemMax": e.currentTarget.dataset.alermmax,
        "AlemMin": e.currentTarget.dataset.alermmin,
        "CollectionValue": e.detail.value,
        "IsIntelligence": ""
      }
      for (var i = 0; i < newArray.length; i++) {
        if (newArray[i].SpotGuid == params.SpotGuid) {
          newArray.splice(i, 1)
        }
      }
      newArray.push(params)

      this.setData({
        ArraysList: newArray
      })
    }
  },

  //获取巡检项
  initData: function() {
    var that = this;
    var param = {
      Type: that.data.TaskType,
      TaskGuid: that.data.RowGuid
    }
    console.log(JSON.stringify(param) + "-------------接口参数")
    var inspectionItem = that.data.PatrolList;
    httpRequest.GetValidateRequest(httpRequest.apiInfo.GetInspectTaskDetailsApi, param, function(data) {
      console.log(JSON.stringify(data) + "--------------接口数据")
      if (data.CollectionList.length <= 0 || data.CollectionList == null || data.CollectionList == [] || data.CollectionList == undefined) {} else {
        var num = that.data.textNam;
        for (var i = 0; i < data.CollectionList.length; i++) {
          if (data.CollectionList[i].SpotType == 2 || data.CollectionList[i].SpotType == "2") {
            num = num + 1;
          }
          that.setData({
            // SpotTypes: data.CollectionList[i].SpotType
            textNam: num
          })
          inspectionItem.push(data.CollectionList[i])
        }
        that.setData({
          PatrolList: inspectionItem
        })
        console.log(that.data.textNam + "------------文本数量")
      }
    }, function(err) {})
  },

  upImg: function() {
    var that = this
    var newImgs = that.data.images
    var imgs_2 = that.data.imgs2
    if (that.data.images.length == 9) {
      this.setData({
        info: '上传数量已超过上限！'
      })
    } else {
      wx.chooseImage({
        count: 9 - that.data.images.length,
        sizeType: ['compressed'],
        sourceType: ['camera'],
        success(res) {
          const tempFilePaths = res.tempFilePaths
          // console.log('选择图片',tempFilePaths)
          for (var i = 0; i < tempFilePaths.length; i++) {
            newImgs.push(tempFilePaths[i])
          }
          // debugger
          for (var i = 0; i < tempFilePaths.length; i++) {
            let path = tempFilePaths[i]
            // console.log('path', path)
            //压缩图片
            wx.compressImage({
              src: path,
              quality: 80,
              success: function(res) {
                console.log(res)
                var tempimgpath = res.tempFilePath
                const uploadFile = wx.uploadFile({
                  url: httpRequest.host + httpRequest.apiInfo.MultipleFileUploadMobileApi,
                  filePath: tempimgpath,
                  name: 'file',
                  header: {
                    "Content-Type": "multipart/form-data"
                  },
                  formData: {
                    FileType: '巡检记录'
                  },
                  success: function(res) {
                    // console.log(typeof(res), typeof(res.data))
                    var param1 = {
                      path: path,
                      path2: tempimgpath,
                      "RowGuid": JSON.parse(res.data).RowGuid,
                      "FileGuid": JSON.parse(res.data).FileGuid
                    }
                    imgs_2.push(param1)
                  },
                  fail: function(err) {
                    that.setData({
                      error: '图片上传失败'
                    })
                    console.error(err)
                  }
                })
                uploadFile.onProgressUpdate((res) => {
                  // console.log("上传进度", res.progress)
                  if (res.progress == 100) {
                    wx.hideLoading()
                  } else {
                    wx.showLoading({
                      title: '图片已上传' + res.progress + '%',
                    })
                  }
                })
              },
              fail: function(err) {
                console.error(('压缩图片失败', err))
              }
            })
          }
          that.setData({
            imgs2: imgs_2,
            images: newImgs,
            picnum: that.data.images.length,
          })
          if (that.data.picnum > 4) {
            that.setData({
              height: 400
            })
          } else {
            that.setData({
              height: 220
            })
          }
        }
      })
    }
  },


  //预览图片
  // previewImg: function(e) {
  //   console.log(e)
  //   // let imgtype = e.currentTarget.dataset.imgtype;
  //   let imglist = e.currentTarget.dataset.imglist
  //   let index = e.currentTarget.dataset.index;
  //   let imgs = [];
  //   for (var i = 0; i < imglist.length; i++) {
  //     imgs.push(imglist[i])
  //   }
  //   wx.previewImage({
  //     current: imgs[index],
  //     urls: imgs,
  //   })
  // },

  //删除图片
  deleteImg: function(e) {
    var that = this;
    console.log(JSON.stringify(e.currentTarget.dataset.filepath))
    wx.showModal({
      title: '删除图片',
      content: '确定删除图片',
      confirmText: '删除',
      success: function (res) {
        if (res.confirm) {
          let index = e.currentTarget.dataset.index;
          let imgs = that.data.images;
          let imgs_2 = that.data.imgs2;
          let filepath = e.currentTarget.dataset.filepath
          for (var i = 0; i < imgs_2.length; i++) {
            if (imgs_2[i].path == filepath) {
              var param = {
                RowGuid: imgs_2[i].RowGuid
              }
              httpRequest.GetValidateRequest(httpRequest.apiInfo.MultipleFileDeleteMobileApi, param,
                function (res) {
                  console.log('删除的结果---', res)
                },
                function (err) {
                  console.error(err)
                })
              imgs_2.splice(i, 1)
            }
          }
          imgs.splice(index, 1)
          that.setData({
            images: imgs,
            picnum: that.data.images.length,
            imgs2: imgs_2
          })
          if (that.data.picnum > 4) {
            that.setData({
              height: 400
            })
          } else {
            that.setData({
              height: 220
            })
          }
        }
      }
    })
  },

  submit: function() {
    var that = this;
    var imgs2 = that.data.imgs2
    var temp = that.data.FileGuid
    if (imgs2.length > 0) {
      for (var i = 0; i < imgs2.length; i++) {
        var param1 = {
          RowGuid: imgs2[i].RowGuid,
          FileGuid: imgs2[i].FileGuid
        }
        temp.push(param1)
      }
      that.setData({
        FileGuid: temp
      })
      // console.log('FileGuid------', that.data.FileGuid)
    }else{
      that.setData({
        error: '请上传图片!'
      })
      return
    }
    if (that.data.PatrolList.length > that.data.ArraysList.length) {
      that.setData({
        info: '请检查巡检项是否有遗漏!'
      })
    } else {
      var Times = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
      if (that.data.GuidType == "Room") {
        var param = {
          "EquipmentRoomContent": {
            "RowGuid": that.data.RowGuid, //任务唯一标识
            "IsAlarm": that.data.IsAlarm, //巡检结果（正常：0，异常：1）
            "TaskRemark": that.data.Remarks, //巡检备注
            "TaskAttatchment": "", //附件(暂时传空字符串"")
            "InspectDate": Times, //巡检日期
            "InspectSpot": that.data.ArraysList, //巡检项集合
            "FileContent": that.data.FileGuid,
          },
          "TaskType": that.data.GuidType,
        }
      } else {
        var param = {
          "EquipInspectTaskContent": {
            "RowGuid": that.data.RowGuid, //任务唯一标识
            "IsAlarm": that.data.IsAlarm, //巡检结果（正常：0，异常：1）
            "TaskRemark": that.data.Remarks, //巡检备注
            "TaskAttatchment": "", //附件(暂时传空字符串"")
            "InspectDate": Times, //巡检日期
            "InspectSpot": that.data.ArraysList, //巡检项集合
            "FileContent": that.data.FileGuid,
          },
          "TaskType": that.data.GuidType,
        }
      }
      // (JObject)JsonConvert.DeserializeObject(that.data.ArraysList)

      console.log(JSON.stringify(param) + "-----------------传参")
      httpRequest.PostValidateRequest(httpRequest.apiInfo.AddTaskRecordApi, param, function(data) {
        console.log(JSON.stringify(data) + "--------------接口数据")
        if (data == true) {
          that.setData({
            success: '新增巡检记录成功!'
          })
          wx.navigateTo({
            url: '../xunjian_Success/xunjian_Success',
          })
        } else {
          that.setData({
            error: '新增巡检记录失败!'
          })
        }
      }, function(err) {})
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

    this.setData({
      customHeight: ((app.globalData.titleBarHeight + app.globalData.statusBarHeight) * 2) + 100
    })

    console.log(JSON.stringify(options) + "------------接收")
    this.setData({
      title: options.RoomName + '巡检任务',
      GuidType: options.GuidType,
      RowGuid: options.TaskId
    })
    if (options.GuidType == 'Room') {
      this.setData({
        TaskType: 0
      })
    } else if (options.GuidType == 'Equip') {
      this.setData({
        TaskType: 1
      })
    }
    // if (options.detail.value == 1){
    //   this.setData({
    //     Submission:true
    //   })
    // }
    this.initData();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})